package com.open.pokergames.comm.userCenter

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import com.dykj.csb.wxapi.Constants
import com.gyf.immersionbar.ImmersionBar
import com.open.pokergames.MainActivity
import com.open.pokergames.R
import com.open.pokergames.base.activity.EventBusTitleBaseActivity
import com.open.pokergames.comm.repository.cache.LocalCache
import com.open.pokergames.comm.repository.entity.LoginDto
import com.open.pokergames.comm.repository.entity.LoginVo
import com.open.pokergames.comm.repository.entity.ResultInfo
import com.open.pokergames.comm.repository.viewModel.SystemViewModel
import com.sinothk.android.utils.XUtils
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class LoginActivity : EventBusTitleBaseActivity(), View.OnClickListener {

    var viewModel: SystemViewModel? = null

    private fun initNoticeTitle() {
        // 标题处理
        ImmersionBar.with(this)
            .statusBarDarkFont(false)
            .keyboardEnable(false)
            .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
            .init()
    }

    // IWXAPI 是第三方app和微信通信的openApi接口
    private var api: IWXAPI? = null

    protected fun regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true)

        // 将应用的appId注册到微信
        api!!.registerApp(Constants.APP_ID)

        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                // 将该app注册到微信
                api!!.registerApp(Constants.APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initNoticeTitle()
        regToWx()

        viewModel = SystemViewModel()

        initView()

        loginBtn.setOnClickListener(this);
        registerBtn.setOnClickListener(this);
        wxLoginBtn.setOnClickListener(this);
    }

    private fun initView() {
        val loginUser = LocalCache.getUser()
        if (loginUser != null && XUtils.string().isNotEmpty(loginUser.phoneNum)) {
            phoneNumEt.setText(loginUser.phoneNum)
            XUtils.view().focusMoveToEnd(phoneNumEt)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun loginCallback(resultInfo: ResultInfo<LoginDto>) {

        if (resultInfo.eventType != "login") {
            return
        }
        hideLoadingDialog()
        when (resultInfo.code) {
            ResultInfo.SUCCESS -> {
                LocalCache.setLoginUser(resultInfo.data)
                LocalCache.setAutoLogin(true)

                XUtils.intent().openActivity(this@LoginActivity, MainActivity::class.java)
                    .finish(true).start()
            }
            else -> {
                XUtils.toast().show(resultInfo.msg)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            loginBtn -> {
                val phoneNum = phoneNumEt.text.toString()
                val password = passwordEt.text.toString()
                if (XUtils.string().isEmpty(phoneNum)) {
                    XUtils.toast().show("手机号码不能为空")
                    return
                }
                if (XUtils.string().isEmpty(password)) {
                    XUtils.toast().show("密码不能为空")
                    return
                }

                showLoadingDialog("正在登录")
                viewModel!!.login(LoginVo(phoneNum, password))


//                //Netty 线程
//                val client = TcpClient()
//                client.start()
            }
            registerBtn -> {
                XUtils.intent().openActivity(this@LoginActivity, RegisterActivity::class.java)
                    .start()
            }

            wxLoginBtn -> {
                val req =  SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                api!!.sendReq(req);
            }
        }
    }
}